const Video = require('./../models/videoModel');
const catchAsync = require('./../utils/catchAsync.js');
const AppError = require('./../utils/appError.js');
const APIFeatures = require('./../utils/apiFeatures.js');
const factory = require('./handlerFactory');
const User = require('../models/userModel');
exports.setVideoUserId = (req, res, next) => {
  // Allow nested routes
  // if (!req.body.tour) req.body.tour = req.params.tourId;
  if (!req.body.user) req.body.user = req.user.id;
  next();
};

//播放次数加1
exports.addPlayCount = catchAsync(async (req, res, next) => {
  let videoId;
  if (req.body.videoId) {
    videoId = req.body.videoId;
  } else if (req.params.videoId) {
    videoId = req.params.videoId;
  } else {
    return next(new AppError('This video is wrong!', 400));
  }

  Video.findOneAndUpdate({ _id: videoId }, { $inc: { playCount: 1 } })
    .then(() => {
      res.status(200).json({
        status: 'success',
        message: 'add playCount',
      });
    })
    .catch((err) => next(err));
});
exports.getOweVideos = async (req, res, next) => {
  // const user = req.user;

  const user = await User.findById(req.user.id).populate('videos');
  // 返回用户的收藏夹数组
  res.status(200).json({
    results: user.videos.length,
    status: 'success',
    videos: user.videos,
    message: 'The User VideosList',
  });
};
exports.getAllVideos = factory.getAll(Video);

exports.getVideo = factory.getOne(Video);
exports.createVideo = factory.createOne(Video);
exports.updateVideo = factory.updateOne(Video);
exports.deleteVideo = factory.deleteOne(Video);
